<template>  
    <div class="ownBox">
        <div class="header marginTop10 marginBottom10">
            <span><redStar/>已选订单：</span>
            <el-button icon="edit" size="small" style="float: right;" v-if="refResh" @click="choicePackingList">选择订单</el-button>
        </div>
        <el-row>
            <el-col :span="24">
                <el-table :data="param.packingInfo" border  style="width: 100%;">
                    <el-table-column prop="orderNo" label="订单号" align="center"></el-table-column>
                    <el-table-column label="预计提箱日期" align="center">
                        <template #default="scope"> {{ formatDate(scope.row.planPickupDate, 2) }}</template>
                    </el-table-column>
                    <el-table-column label="下单日期" align="center">
                        <template #default="scope"> {{ formatDate(scope.row.createTime, 2) }} </template>
                    </el-table-column>
                    <el-table-column v-if="refResh" prop="packingAllocationQuantity"  label="已开箱量" align="center"> </el-table-column>
                    <el-table-column v-if="refResh" prop="boxQuantity" label="未开箱量" align="center">
                        <template #default="scope">{{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}</template>
                    </el-table-column>
                    <el-table-column v-if="param.packingInfo.length  > 1 && refResh" prop="needPackingNum" label="需开箱量" align="center"> 
                        <template #default="scope">{{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}</template>
                    </el-table-column>
                    <el-table-column v-else-if="refResh" label="需开箱量" align="center">
                        <el-input v-model="needBoxNum" type="number" :min="1" style="width: 100%;" @change="handleSelectionChange"/>
                        <!-- <template #default="scope">
                            <el-input v-model="scope.row.needPackingNum" type="number" :min="1" style="width: 100%;" @change="handleSelectionChange"/>
                        </template> -->
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-row class="marginTop20">
            <el-col :span="24">箱型/箱况/箱量：</el-col>
            <el-col :span="24">
                <el-table :data="param.boxTypeInfo" border  style="width: 100%;margin-top: 10px;">
                    <el-table-column label="箱型" align="center">
                        <template #default="scope">{{formatBoxType(scope.row.boxType)}}</template>
                    </el-table-column>
                    <el-table-column label="箱况" align="center">
                        <template #default="scope">{{formatBoxCondition(scope.row.boxCondition)}}</template>
                    </el-table-column>
                    <el-table-column prop="boxQuantity" v-if="refResh" label="箱量" align="center"> 
                        <template #default="scope">{{totalIssueBoxNum}}</template>
                    </el-table-column>
                    <el-table-column prop="boxQuantity" v-else label="箱量" align="center"></el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar/>成本价:</el-col>
            <el-col :offset="1" :span="15" class="rentInPrice">
                <el-input v-model="param.rentInPrice" placeholder="请输入成本价" :parser="parserNumber" :formatter="formatterNumber">
                    <template #prefix>
                        <el-select v-model="param.rentInCurrency" style="width: 80px;">
                            <el-option label="$" value="USD"></el-option>
                            <el-option label="￥" value="CNY"></el-option>
                        </el-select>
                    </template>
                </el-input>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar/>放箱指令号:</el-col>
            <el-col :offset="1" :span="15"><el-input v-model="param.instruction" placeholder="请输入指令号" /></el-col>
        </el-row>
        
        <el-row class="marginTop10 text-right"> 
            <el-col :span="6"><redStar />提箱单有效期范围:</el-col>
            <el-col :offset="1" :span="15">
                <el-date-picker v-model="param.packingValidityPeriod" type="daterange" range-separator="~"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
            </el-col>
        </el-row>
        
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar />堆场名称:</el-col>
            <el-col :offset="1" :span="15">
                <yardSelect v-model="param.yardName" :selectName="'yardName'" :refResh="refResh" :boxEastYardId="param.boxEastYardId" :yardName="param.yardName" :needInfo="true" @yardId="yardInfoData" :placeholder="'请输入堆场名称'"></yardSelect>
            </el-col>   
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar />堆场地址:</el-col>
            <el-col :offset="1" :span="15">
                <el-input v-model="yardInfo.yardAddress" disabled style="width: 100%;" placeholder="请输入"></el-input>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar />联系人:</el-col>
            <el-col :offset="1" :span="15">
                <el-select v-model="yardInfo.contacts" @change="handleYardContactsChange">
                    <el-option v-for="item in yardInfo.yardContacts" :key="item.yardContactSerialNo" :label="item.contacts"
                    :value="item">
                    </el-option>
                </el-select>
            </el-col>
        </el-row>

        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar />联系电话:</el-col>
            <el-col :offset="1" :span="15">
                <el-input v-model="yardInfo.tel" disabled style="width: 100%;" placeholder="请输入"></el-input>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar />邮箱:</el-col>
            <el-col :offset="1" :span="15">
                <el-input v-model="yardInfo.email" disabled style="width: 100%;" placeholder="请输入"></el-input>
            </el-col>
        </el-row>
        <el-row class="marginTop10 text-right">
            <el-col :span="6"><redStar />堆场作业时间:</el-col>
            <el-col :offset="1" :span="15">
                <el-input v-model="yardInfo.workTime" disabled style="width:100%" placeholder="请输入" />
            </el-col>
        </el-row>
       
        <template v-if="yardInfo.containerClassify">
            <el-row class="marginTop10 text-right">
                <el-col :span="6"><redStar/>箱源:</el-col>
                <el-col :offset="1" :span="6">
                    <el-input v-model="{5:'自有箱',10:'代管箱',15:'外调箱'}[yardInfo.containerClassify]" disabled placeholder="请输入" />
                </el-col>
            </el-row>
        </template>
        <template v-if="yardInfo.companyName">
            <el-row class="marginTop10 text-right">
                <el-col :span="6"><redStar/>箱东:</el-col>
                <el-col :offset="1" :span="6">
                    <el-input v-model="yardInfo.companyName" disabled placeholder="请输入" />
                </el-col>
            </el-row>
        </template>
        <el-row class="marginTop10">
            <el-col :span="6" class="text-right">箱号:</el-col>
            <el-col :offset="10" :span="6"><el-button @click="choiceBox" icon="edit" style="float: right;">选择箱号</el-button></el-col>
            <el-col :offset="6" :span="18" class="marginTop10">
                <!-- <el-row style="border: 1px solid #ccc; margin-top:10px; color: #666;">
                    <template v-for="(item,index) in param.selectedContainerList" :key="index">
                        <el-col :span="8" class="containerNo-box text-center" style="border: 1px solid #ccc;">{{item.containerNo}}</el-col>
                    </template>
                </el-row> -->
                <template v-for="(item,index) in param.selectedContainerList" :key="index">
                    {{item.containerNo}}<template v-if="index < (param.selectedContainerList.length - 1)">、</template>
                </template>
            </el-col>
        </el-row>
        <el-row class="marginTop10">
            <el-col :span="6" class="text-right">附件：</el-col>
            <el-col :span="18">
                <ImgUpload ref="packingRef" :displayType="3" :urlList="fileList" :limit="10" :showNumber="4" :type="'jpg/jpeg/png/zip/pdf/doc/docx'" :drag="true"/>
            </el-col>
        </el-row>
        <el-row class="marginTop10">
            <el-col :span="6" class="text-right">备注：</el-col>
            <el-col :span="18">
                <el-input v-model="param.remark" type="textarea" placeholder="请输入内容" />
            </el-col>
        </el-row>
        <!-- <div class="text-center marginTop20">
            <el-button type="primary" v-if="refResh" @click="handleSubmit">提交</el-button>
            <el-button type="primary" v-else @click="drawerPackingOpen">提交</el-button>
        </div> -->
        <el-row class="marginTop50">
            <el-col :offset="13" :span="4">
                <el-button type="primary" v-if="refResh" @click="handleSubmit">提交</el-button>
                <el-button type="primary" v-else @click="drawerPackingOpen">提交</el-button>
            </el-col>
        </el-row>
    </div>
    <el-dialog v-model="param.dialogPacking" title="租箱订单选择" width="1300">
        <AllPacking :subassemblyInfo="orderSelectionInfo" @config="config" @checkOrderList="checkOrderList" :orderType="props.orderType" :currentNumber="param.currentNumber" :sources="5" :disable="true"/>
    </el-dialog>

    <el-dialog v-model="param.drawerSelectBox" v-if="param.drawerSelectBox" title="可选择集装箱" width="550">  <!--可选集装箱弹窗-->
        <ContainerList @selectedContainer="selectedContainer" :boxEastYardId="param.boxEastYardId" :boxInfo="boxInfos"></ContainerList>
    </el-dialog>
</template>
<script lang="ts" setup>
import { reactive,ref, computed, onMounted, inject,onActivated,watch,provide,defineExpose } from 'vue'
import { formatDate, formatBoxType, formatBoxCondition } from '@/utils'
import redStar from '@/views/components/redStar.vue';
import AllPacking from '@/views/placingOrder/exportOrder/component/allPacking';
import ContainerList from '@/views/placingOrder/exportOrder/component/containerList';
import yardSelect from '@/components/citySelect/yardSelect.vue';
// import imgUpload from '@/components/upload/index.vue'
import ImgUpload from '@/components/upload/uploadFiles-Images.vue'
import { addPacking ,getPackingData,getExpiredReopen} from '@/api/orderManage/packing'
import { ElMessage } from 'element-plus';
const boxInfo = () => {
  return param.boxTypeInfo
}
provide('boxInfo', boxInfo);
// const fun = inject('packingInfo')
const injectInfn = [];
const emit = defineEmits(['closeDialog'])
//props.packingInfo.orderType 5 - 租箱， 10 - 回调，  （200 - 售箱）
const props = defineProps({
  packingInfo: {
    type: Object,
    default: () => {}
  },
  orderType:{
    type: Number,
    default: 0  // 5 - 租箱， 10 - 回调 ，（200 - 售箱）
  },
  tag:{
    type:String, // 组件调用来运标记
    default: ''
  }
})

const config = reactive({
    disable: true, //控制搜索框显示/隐藏
    sources: 'internal',

})
const param = reactive({
    oldPackingId:'',
    dialogPacking:false,
    packingInfo: props.packingInfo,
    orderNo:"",// 订单号
    planPickupDate:"",// 预计提箱日期
    createTime:"", //下单日期
    packingAllocationQuantity:"",// 已开箱量
    boxQuantity:"",// 未开箱量
    needPackingNum:"1",// 需开箱量
    boxTypeInfo:[], //箱型/箱况/箱量
    packingValidityPeriod:"",
    selectedContainerList:[],
    yardName:"",
    boxEastYardId:"",
    instruction:"",
    remark:"",//备注
    drawerPacking:false,
    drawerSelectBox: false, // 可选集装箱弹窗
    stagingData: props.packingInfo, // 暂存数据
    containerNoList: [], // 箱号"[{\"containerId\":1,\"containerNo\":\"2222\"}]" jc0706
    boxType: injectInfn[0]?.boxType,
    boxCondition: injectInfn[0]?.boxCondition,
    yardContactSerialNo:"",
    currentNumber: "", //订单内开提箱单 当前单号
    rentInPrice:'1.00', //成本价
    rentInCurrency:'USD'//成本价币种
})
// onActivated(() => {
//     // console.log("onActivated")
// })
onMounted(() => { 
    param.currentNumber = props.packingInfo[0]?.orderNo  // 当前订单号
    param.boxTypeInfo = []
    needBoxNum.value = param.packingInfo[0]?.boxQuantity - param.packingInfo[0]?.packingAllocationQuantity // 需开箱量
    param.packingInfo.forEach((item: any,index: number) => {
        let info = {
            "boxType":item.boxType,
            "boxCondition":item.boxCondition,
            "boxQuantity":item.boxQuantity 
        }
        item.needPackingNum = 1
        param.boxType = item.boxType
        param.boxCondition = item.boxCondition
        param.boxTypeInfo.push(info)
        // subassemblyInfo.carryCityId = item.carryCityId
        // subassemblyInfo.agentName = item.agentName
        // subassemblyInfo.boxType = item.boxType
        // subassemblyInfo.boxCondition = item.boxCondition
        
    })
})
const orderSelectionInfo  = reactive({
    orderType: "5", //  5 - 租箱， 10 - 回调 ，（200 - 售箱）
    agentName:"",
    boxType:"",
    boxCondition:"",
    orderNo:"",
    carryCityId:"",
    returnCityId:"",
    info:{}
})

//详情接口
const fileList=ref([]) //附件默认
const needBoxNum = ref(0)
const showInfo = (row: any) => {
  if (!row.id) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  getPackingData(row.id).then((res: any) => {
    const data = res.data
    let packingValidityPeriodList=[]
    if(data.packingValidityPeriodStart){
        packingValidityPeriodList.push(data.packingValidityPeriodStart)
        packingValidityPeriodList.push(data.packingValidityPeriodEnd)
    }
    param.packingValidityPeriod = packingValidityPeriodList
    param.packingInfo = JSON.parse(data.orderList)
    needBoxNum.value = param.packingInfo[0]?.boxQuantity - param.packingInfo[0]?.packingAllocationQuantity

    param.boxTypeInfo = []
    let boxInfo = {
        boxType:data.boxType,
        boxCondition:data.boxCondition,
        boxQuantity:data.totalQuantity-data.packedQuantity
    }
    param.boxTypeInfo.push(boxInfo) 
    param.instruction=data.instruction
    param.selectedContainerList = JSON.parse(data.containerNoList)
    fileList.value=JSON.parse(data.packingFileList)
    param.oldPackingId=data.id
    param.yardName=data.yardName
    param.boxEastYardId=data.yardId
    param.remark=data.remark
    param.rentInCurrency = data.rentInCurrency
  })
};
//重开提交
const drawerPackingOpen = () => {
    let packingFileList = packingRef.value.resultList || []
    let data = {
    oldPackingId: param.oldPackingId,
        packingValidityPeriodStart: param.packingValidityPeriod[0],
        packingValidityPeriodEnd: param.packingValidityPeriod[1],
        instruction:param.instruction?.trim(),
        boxEastYardId: param.boxEastYardId,
        yardContactSerialNo: param.yardContactSerialNo,
        packingFileList:JSON.stringify(packingFileList), // 附件
        remark: param.remark,
    }

    getExpiredReopen(data).then(res => {
        if (res.code == "00000") {
            ElMessage.success("提交成功")
            refResh.value=true
            emit('closeDialog',props.tag)
        }else{
            ElMessage.error(res.msg)
        }
    }).catch(err => {
        console.log("ERROR:",err)
    })
}
const refResh=ref(true) //判断是否是重开
const openBox = (info) => {
    refResh.value=false
    showInfo(info)
}

//堆场组件 emit 
const yardInfo = ref({
    id:'',
    yardContacts:'',
    yardAddress:'',
    workTime:'',
    contacts:'',
    companyName:'',
    containerClassify:'',
    email:'',
    tel:''
})

//查询所有可开提箱单的订单（针对当前角色）
const choicePackingList = () => {
    orderSelectionInfo.boxType = props.packingInfo[0]?.boxType
    orderSelectionInfo.boxCondition = props.packingInfo[0]?.boxCondition
    orderSelectionInfo.carryCityId = props.packingInfo[0]?.carryCityId
    orderSelectionInfo.returnCityId = props.packingInfo[0]?.returnCityId
    param.dialogPacking = true
}

//选中的可开提箱单的订
const checkOrderList = (list: any) => {
    param.dialogPacking = false
    if(list.length == 0) return param.packingInfo = param.packingInfo.filter(item => item.orderNo == param.currentNumber) // 未选中订单 不进行后续操作

    param.packingInfo = param.stagingData.concat(list)
    param.packingInfo = Array.from(new Map(param.packingInfo.map(item => [item.orderNo, item])).values());
    param.boxTypeInfo = []
    param.packingInfo.forEach((item: any,index: number) => {
        if(index == 0){
            let info = {
                "boxType":item.boxType,
                "boxCondition":item.boxCondition,
                "boxQuantity":item.boxQuantity
            }
            param.boxTypeInfo.push(info)
            param.boxType = item.boxType
            param.boxCondition = item.boxCondition
        }
        
    })
    needBoxNum.value = param.packingInfo[0]?.boxQuantity - param.packingInfo[0]?.packingAllocationQuantity
}

// 堆场信息
const yardInfoData = (id: string, info: any) => {
  if (info) {
    param.yardName = info.yardName
    yardInfo.value.yardContacts = info.yardContacts ? JSON.parse(info.yardContacts) : []
    yardInfo.value.yardAddress = info.yardAddress
    yardInfo.value.workTime = info.workTime
    yardInfo.value.id = info.id
    param.boxEastYardId = info.id
    //获取联系人&&默认第一个
    handleYardContactsChange(yardInfo.value.yardContacts[0])
  }
}
//联系人切换
const handleYardContactsChange = (val: any) => {
  if (!val) return
  console.log(val)
  yardInfo.value.contacts = val.contacts
  param.contacts = val.contacts //  to pass jiaoyan
  yardInfo.value.tel = val.tel
  yardInfo.value.email = val.email
  yardInfo.value.yardContactSerialNo = val.yardContactSerialNo
  param.yardContactSerialNo = val.yardContactSerialNo
}

//查询所有可选箱号
const boxInfos = ref({
    boxType:'',
    boxCondition:''
})
const choiceBox = () => {
   if(!param.boxEastYardId) return ElMessage.error('请先选择堆场！') 
    boxInfos.value.boxType = props.packingInfo[0]?.boxType
    boxInfos.value.boxCondition =  props.packingInfo[0]?.boxCondition
    param.drawerSelectBox = true
}

const selectedContainer = (list: any) => {
    param.drawerSelectBox = false
    param.selectedContainerList = list
    param.containerNoList = [] // [{\"containerId\":1,\"containerNo\":\"2222\"}]
    list.map((item: any) => {
        let containerItem = {
            containerId:item.id,
            containerNo:item.containerNo
        }
        param.containerNoList.push(containerItem)
    })
}

const packingRef = ref([])
const handleSubmit = () => {
    let orderListInfo = []
    if(param.packingInfo.length == 1){
        param.packingInfo.forEach((item: any) => {
            let itemInfo= {
                orderId: item.id, 
                orderNo: item.orderNo, 
                planPickupDate: item.planPickupDate, 
                createTime: item.createTime, 
                boxQuantity: item.boxQuantity, 
                needPackQuantity:needBoxNum.value
            }
            orderListInfo.push(itemInfo)
        })
    }else{
        param.packingInfo.forEach((item: any) => {
            let needPackQuantity = item.boxQuantity - item.packingAllocationQuantity
            let itemInfo = { 
                orderId: item.id, 
                orderNo: item.orderNo, 
                planPickupDate: item.planPickupDate, 
                createTime: item.createTime, 
                boxQuantity: item.boxQuantity, 
                needPackQuantity: needPackQuantity 
            }
            orderListInfo.push(itemInfo)
        })
    }
    const packingFileList = packingRef.value.fileList || []
    let requestInfo = {
        orderType: props.orderType,
        orderList: JSON.stringify(orderListInfo),
        instruction:param.instruction?.trim(), // 放箱指令号
        packingValidityPeriodStart: param.packingValidityPeriod[0],
        packingValidityPeriodEnd: param.packingValidityPeriod[1],
        yardName: param.yardName?.trim(),//堆场名称
        boxEastYardId: param.boxEastYardId, // 堆场id
        containerNoList:JSON.stringify(param.containerNoList), // 箱号"[{\"containerId\":1,\"containerNo\":\"2222\"}]" jc0706
        remark: param.remark,
        packingFileList:JSON.stringify(packingFileList), // 附件
        boxType: param.boxType,
        boxCondition: param.boxCondition,
        yardContactSerialNo: param.yardContactSerialNo,
        containerClassify:5,  // 5:自有箱  15：外调箱 
        rentInPrice:param.rentInPrice,
        rentInCurrency:param.rentInCurrency

    }
    addPacking(requestInfo).then(res => {
        if (res.code == "00000") {
            ElMessage.success("提交成功")
            emit('closeDialog',props.tag)
        }else{
            ElMessage.error(res.msg)
        }
    }).catch(err => {
        console.log("ERROR:",err)
    })
    
}

const totalIssueBoxNum = computed(() => {
    let total = 0
    let ykTltal = 0
    if(param.packingInfo.length == 1) return needBoxNum.value || "--" 
    param.packingInfo.forEach((item: any) => {
        total += item.boxQuantity
        ykTltal += item.packingAllocationQuantity
    })
    return total - ykTltal
})

const handleSelectionChange = (val: any) => {
    // 只有订单选择一个时 需开箱量才可修改时
    if(val < 1){
        val = 1
    } 
    param.packingInfo[0].needPackingNum = val
    needBoxNum.value = val

}

const formatterNumber = (value:any) =>{ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    return (val- 0)
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}

const parserNumber = (value) => {
  return value.replace(/[^\d.]/g, '')
    .replace(/(\.\d*)\./g, '$1')
    .replace(/^(\d{5})\d+/, '$1')
    .replace(/\.(\d{2})\d+/, '.$1');
};

defineExpose({
    openBox
})
</script>

<style lang="scss" scoped>
.ownBox{
    padding: 0 20px;
}
.rentInPrice{
    :deep(.el-select__wrapper) {
      box-shadow: none !important;
      // height: 30px;
      // border-radius: 0;
  }
}

</style>